package org.glut.controller;

import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import org.glut.serialport.manager.SerialPortManager;
import org.glut.serialport.utils.ByteUtils;
import org.glut.serialport.utils.ShowUtils;
import org.glut.service.SerialPortMsg;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.swing.*;
import java.util.ArrayList;

/**
 * @author 啊林
 * @date 2022/1/13
 * @time 1:30
 */
@Controller
public class SerialPortController {
    private String serialPort;
    private int baudrate;
    private SerialPort connPort = null;

    @RequestMapping("/findPorts")
    @ResponseBody
    public ArrayList<String> findPorts() {
        return SerialPortManager.findPorts();
    }

    @RequestMapping("/connSerial")
    @ResponseBody
    public boolean connSeria(String serialPort, String baudrate) {
        try {
            System.out.println(serialPort + " + " + baudrate);
            if (serialPort != "" && baudrate != null){
                this.serialPort = serialPort;
                this.baudrate = Integer.parseInt(baudrate);
                connPort = SerialPortManager.openPort(this.serialPort, this.baudrate);
                // 添加串口监听
                SerialPortManager.addListener(connPort, new SerialPortManager.DataAvailableListener() {

                    @Override
                    public void dataAvailable() {
                        byte[] data = null;
                        try {
                            if (connPort == null) {
                                ShowUtils.errorMessage("串口对象为空，监听失败！");
                            } else {
                                // 读取串口数据
                                data = SerialPortManager.readFromPort(connPort);
                            }
                        } catch (Exception e) {
                            ShowUtils.errorMessage(e.toString());
                            // 发生读取错误时显示错误信息后退出系统
                            System.exit(0);
                        }
                    }
                });
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return connPort != null;
    }

    @RequestMapping("/closePort")
    @ResponseBody
    public boolean closePort() {
        if (connPort != null) {
            SerialPortManager.closePort(connPort);
            connPort = null;
            return true;
        }
        return false;
    }

    @RequestMapping("/getserialStatus")
    @ResponseBody
    public boolean getserialStatus() {
        if (connPort != null) {
            return true;
        }
        return false;
    }
}
